<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\RoleCreateRequest;
use App\Http\Requests\Admin\RoleUpdateRequest;
use App\Models\Admin\Dictionary;
use App\Models\Admin\Permission;
use App\Models\Admin\Role;
use Auth;
use DB;
use Illuminate\Http\Request;

class RoleController extends Controller
{
    protected $fields = [
        'id' => '',
        'name'        => '', //角色名
        'description' => '', //描述
        'permissions' => [], //所有权限
        'dictionarys' => [], //所有字段
    ];

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        if ($request->ajax()) {
            $data                 = array();
            $data['draw']         = $request->get('draw');
            $start                = $request->get('start');
            $length               = $request->get('length');
            $order                = $request->get('order');
            $columns              = $request->get('columns');
            $search               = $request->get('search');
            $data['recordsTotal'] = Role::count();
            if (strlen($search['value']) > 0) {
                $data['recordsFiltered'] = Role::where(function ($query) use ($search) {
                    $query->where('name', 'LIKE', '%' . $search['value'] . '%')
                        ->orWhere('description', 'like', '%' . $search['value'] . '%');
                })->count();
                $data['data'] = Role::where(function ($query) use ($search) {
                    $query->where('name', 'LIKE', '%' . $search['value'] . '%')
                        ->orWhere('description', 'like', '%' . $search['value'] . '%');
                })
                    ->skip($start)->take($length)
                    ->orderBy($columns[$order[0]['column']]['data'], $order[0]['dir'])
                    ->get();
            } else {
                $data['recordsFiltered'] = Role::count();
                $data['data']            = Role::
                    skip($start)->take($length)
                    ->orderBy($columns[$order[0]['column']]['data'], $order[0]['dir'])
                    ->get();
            }
            return response()->json($data);
        }

        return view('admin.role.index');
    }

    //递归生成树
    public function generateTree($cate, $name = 'child', $f_pid = 0)
    {
        $arr = array();
        foreach ($cate as $v) {
            if ($v['f_pid'] == $f_pid) {
                $v[$name] = self::generateTree($cate, $name, $v['id']);
                $arr[]    = $v;
            }
        }
        return $arr;
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $data = $this->fields;

        //取出所有的菜单【然后根据listorder进行升序排序】
        $menu = \App\Models\Admin\Menu::orderBy('listorder', 'asc')->get()->toArray();
        //取出所有的顶级菜单【依据f_pid=0, 然后根据listorder进行升序排序】
        // $fatherMenu = \App\Models\Admin\Menu::where('f_pid', '=', 0)->orderBy('listorder', 'asc')->get()->toArray();
        //取出所有的二级菜单【依据f_pid!=0, 然后根据listorder进行升序排序】
        // $menu = \App\Models\Admin\Menu::where('f_pid', '=', 0)->orderBy('listorder', 'asc')->get()->toArray();
        $menu        = $this->generateTree($menu);
        $permissions = Permission::all()->toArray();

        //遍历一级菜单
        foreach ($menu as $k => $v) {
            //遍历二级菜单
            foreach ($v['child'] as $key => $value) {
                //二级菜单的id
                $secondMenuId = $value['id'];
                //通过二级菜单的id找出二级菜单下的权限
                $menu[$k]['child'][$key]['child'] = array_filter($permissions, function ($permission) use ($secondMenuId) {
                    if ($permission['f_pid'] == $secondMenuId) {
                        return \Gate::check($permission['name']);
                    }
                    return false;
                });
                //如果二级的子级没有则删除
                if (count($menu[$k]['child'][$key]['child']) == 0) {
                    unset($menu[$k]['child'][$key]);
                }
            }
            //如果顶级的子级则要删除
            if (count($menu[$k]['child']) == 0) {
                unset($menu[$k]);
            }
        }

        $rolelist = [];
        $dictionary = [];
        //数据字段-通过角色id去获得
        foreach (Auth::guard(config('inventory.base.guard'))->user()->roles as $role) {
            $rolelist[] = $role->id;
        }
        if (Auth::user()->id == '1') {
            $dictionary = Dictionary::all()->toArray();
        } else {
            $dictionary = Dictionary::join('admin_dictionary_role', 'admin_dictionary_role.dictionary_id', '=', 'admin_dictionary.id')->select(['admin_dictionary.*'])->whereIn('admin_dictionary_role.role_id', $rolelist)->get()->toArray();
        }

        $data['menu']          = $menu;
        $data['dictionaryAll'] = $dictionary;

        return view('admin.role.create', $data);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param RoleCreateRequest $request
     * @return \Illuminate\Http\Response
     */
    public function store(RoleCreateRequest $request)
    {
        $role = new Role();

        $input       = $request->all();
        $permissions = isset($input['permissions']) ? $input['permissions'] : [];
        $dictionarys = isset($input['dictionarys']) ? $input['dictionarys'] : [];
        $role = $role->create($input);
        $role->permissions()->sync($permissions);
        $role->dictionarys()->sync($dictionarys);

        //写日志
        event(new \App\Events\userActionEvent('\App\Models\Admin\Role', $role->id, 1, "用户" . Auth::user()->name . "{" . Auth::user()->id . "}添加角色" . $role->name . "{" . $role->id . "}"));

        return redirect('/admin/role')->withSuccess('添加成功！');
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $id = $id;
        $role = Role::find($id);

        if (!$role) {
            return redirect('/admin/role')->withErrors("找不到该角色!");
        }

        //获得该角色下的权限id-记得转为数组
        $permissions = $role->permissions->pluck('id')->toArray();
        //给data,几个默认字段
        $data                = $this->fields;
        $data['permissions'] = $permissions;

        //前端需要回填的数据
        $data['id']          = $id;
        $data['name']        = $role->name;
        $data['description'] = $role->description;

        //当前用户有的权限-取出所有的菜单【然后根据listorder进行升序排序】
        $menu        = \App\Models\Admin\Menu::orderBy('listorder', 'asc')->get()->toArray();
        $menu        = $this->generateTree($menu);
        $permissions = Permission::all()->toArray();
        //遍历一级菜单
        foreach ($menu as $k => $v) {
            //遍历二级菜单
            foreach ($v['child'] as $key => $value) {
                //二级菜单的id
                $secondMenuId = $value['id'];
                //通过二级菜单的id找出二级菜单下的权限
                $menu[$k]['child'][$key]['child'] = array_filter($permissions, function ($permission) use ($secondMenuId) {
                    if ($permission['f_pid'] == $secondMenuId) {
                        return \Gate::check($permission['name']);
                    }
                    return false;
                });
                //如果二级的子级没有则删除
                if (count($menu[$k]['child'][$key]['child']) == 0) {
                    unset($menu[$k]['child'][$key]);
                }
            }
            //如果顶级的子级则要删除
            if (count($menu[$k]['child']) == 0) {
                unset($menu[$k]);
            }
        }

        $rolelist = [];
        $dictionary = [];
        //获得字典
        if (Auth::user()->id == '1') {
            $dictionarys           = Dictionary::all()->toArray();
            $data['dictionaryAll'] = $dictionarys;
        } else {
            //获取到所有的视图字段
            foreach (Auth::guard(config('inventory.base.guard'))->user()->roles as $role) {
                $rolelist[] = $role->id;
            }
            $dictionarys           = Dictionary::join('admin_dictionary_role', 'admin_dictionary_role.dictionary_id', '=', 'admin_dictionary.id')->select(['admin_dictionary.*'])->whereIn('admin_dictionary_role.role_id', $rolelist)->get()->toArray();
            $data['dictionaryAll'] = $dictionarys;
        }

        //当前角色有的字段
        $dictionary = DB::select('select * from admin_dictionary_role where role_id = ?', [$id]);
        if ($dictionary) {
            $dictionarys = [];
            foreach ($dictionary as $v) {
                $dictionarys[] = $v->dictionary_id;
            }
        }

        $data['menu']        = $menu;
        return view('admin.role.edit', $data)->with(array('dictionarys' => $dictionarys));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param PermissionUpdateRequest|Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(RoleUpdateRequest $request, $id)
    {
        $role = Role::find($id);
        //加上是否非法数据判断
        if (!$role) {
            return redirect('/admin/role')->withErrors("找不到该角色!");
        }

        //获得前端提交过来的数据
        $input       = $request->all();
        $permissions = isset($input['permissions']) ? $input['permissions'] : [];
        $dictionarys = isset($input['dictionarys']) ? $input['dictionarys'] : [];
        $role->update($input);
        $role->permissions()->sync($permissions);
        $role->dictionarys()->sync($dictionarys);

        //写日志
        event(new \App\Events\userActionEvent('\App\Models\Admin\Role', $role->id, 3, "用户" . Auth::user()->name . "{" . Auth::user()->id . "}编辑角色" . $role->name . "{" . $role->id . "}"));
        return redirect('/admin/role')->withSuccess('修改成功！');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $role = Role::find($id);

        //加上是否非法数据判断
        if (!$role) {
            return redirect('/admin/role')->withErrors("找不到该角色!");
        }

        //有该角色的用户解绑
        $role->users()->detach();
        //和权限解绑
        $role->permissions()->detach();
        //和角色组解绑
        $role->groups()->detach();
        //和字典解绑
        $role->dictionarys()->detach();

        //如果删除成功
        if ($role) {
            $role->delete();
        } else {
            return redirect()->back()
                ->withErrors("删除失败");
        }

        //写日志
        event(new \App\Events\userActionEvent('\App\Models\Admin\Role', $role->id, 2, "用户" . Auth::user()->name . "{" . Auth::user()->id . "}删除角色" . $role->name . "{" . $role->id . "}"));
        return redirect()->back()
            ->withSuccess("删除成功");
    }
}
